package promote.brozen.netty.jav.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.spi.AsynchronousChannelProvider;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.LockSupport;

/**
 * @author Brozen
 * @date 2020/9/27 1:05 PM
 * @email brozen@qq.com
 */
public class AioServer {

    public AsynchronousServerSocketChannel ssc;

    public AioServerAcceptor acceptor;

    public void start() throws IOException {

        // 初始化
        acceptor = new AioServerAcceptor();
        ssc = AsynchronousServerSocketChannel.open();

        // 设置一下服务端接收数据的线程池
        // 不知道为什么，这样设置线程池失败
        AsynchronousChannelProvider provider = AsynchronousChannelProvider.provider();
        AsynchronousChannelGroup acg = provider.openAsynchronousChannelGroup(Executors.newSingleThreadExecutor(r -> {
            Thread thread = new Thread(r);
            thread.setName("SCP-Server");
            return thread;
        }), 0);// warning 这里的第二个参数initialSize设置为1的话，启动之后无法连接，不知道为啥
        ssc = provider.openAsynchronousServerSocketChannel(acg);

        // 启动服务端
        ssc.bind(new InetSocketAddress("127.0.0.1", 8090));
        ssc.accept(this, new AioServerAcceptor());

        System.out.println("启动成功！");
        LockSupport.park();
    }

    public static void main(String[] args) throws IOException {
        new AioServer().start();
    }

}
